package com.lagou.service.impl;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;

import com.lagou.pojo.AuthCode;
import com.lagou.repository.AuthCodeRepository;
import com.lagou.service.EmailService;
import com.lagou.service.VertifyCodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;

import java.util.*;

/**
 * @ClassName: VerifyCodeServiceImpl
 * @Auther: Jerry
 * @Date: 2020/10/22 19:40
 * @Desctiption: TODO
 * @Version: 1.0
 */
@Service
public class VerifyCodeServiceImpl implements VertifyCodeService {

    private Logger logger = LoggerFactory.getLogger(VerifyCodeServiceImpl.class);

    @Autowired
    private AuthCodeRepository repository;

    @Reference
    private EmailService emailService;

    @Override
    public Boolean create(String email) {
        // 生成验证码
        String code = generateCode();
        logger.info("generate code is [{}]", code);

        // 保存数据库
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Date now = new Date();
        authCode.setCreateTime(now);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.MINUTE, 10);
        Date time = calendar.getTime();
        authCode.setExpireTime(time);

        AuthCode authCodeNew = repository.save(authCode);
        if (authCodeNew == null) {
            throw new RuntimeException("生成验证码失败");
        }

        // 调用邮箱微服务发送邮件
        Boolean result = emailService.sendToEmail(email, code);
        return result;
    }

    /**
     * 生成6位随机验证码
     * @return {@link String}
     */
    private String generateCode() {
        StringBuilder code = new StringBuilder("");
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            //每次随机出一个数字（0-9）
            int r = random.nextInt(10);
            //把每次随机出的数字拼在一起
            code.append(r);
        }
        return code.toString();
    }


    @Override
    public Integer validate(String email, String code) {
        logger.info("request param[{}], [{}]", email, code);
        // 校验验证码是否正确 0正确1错误2超时
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        Optional<AuthCode> optional = repository.findOne(example);

        // 查询结果是否为空
        if (!optional.isPresent()) {
            return 1;
        }
        AuthCode validateAuthCode = optional.get();
        // 校验是否过期
        DateField minute = DateField.MINUTE;
        int timeLength = 0;
        Date now = new Date();
        boolean expired = DateUtil.isExpired(now, minute, timeLength, validateAuthCode.getExpireTime());
        logger.info("code isExpired[{}]", expired);
        return expired == false ? 0 : 2;
    }

    public static void main(String[] args) {
        DateTime expireTime = DateUtil.parse("2020-10-27 14:30:00");
        Date now = new Date();
        DateField minute = DateField.MINUTE;
        int timeLength = 0;
        boolean expired = DateUtil.isExpired(now, minute, timeLength, expireTime);
        System.out.println(expired);
    }

}
